<template>
    <el-dialog v-if="dialogVisible" :close-on-click-modal='false' title="广告复制" :visible.sync="dialogVisible" @close="resetForm('copyForm')" width="700px">
        <div class="copy_box flexbox">
            <div class="copy_left flex">
                <div class="flexbox flexcenter flexbetween" style="margin-bottom: 18px;">
                    <span style="color:#17233D">已选广告创意</span> 
                     <el-popover
                        placement="top-start"
                        width="360"
                        trigger="hover"
                       >
                       <div style="margin: 8px 12px;display: flex;flex-direction: column;">
                         <div v-for="(item,index) in subForm.creatives" :style="{borderBottom: index + 1 == subForm.creatives.length ?'none':'1px solid #E8EAEC'}" style="padding:12px 0;">
                            <div>{{item.ad_name}}</div>
                            <div style="color: #B4B7BD;font-size: 12px;margin: 4px 0;">广告 ID：{{item.ad_id}}</div>
                            <div style="color: #B4B7BD;font-size: 12px;">出价：${{item.bid_price || 0}}</div>
                        </div>
                       </div>
                        <span slot="reference" style="border-radius: 6px;background: rgba(165, 177, 209, 0.10);padding: 6px 12px;color: #165DFF;">
                        {{subForm.creatives.length}}个广告创意
                    </span>
                    </el-popover>

                    
                </div>
                <el-form label-position="top" size="small" :model="subForm" :hide-required-asterisk='true' ref="copyForm" class="dialog_form">
                    <el-form-item label="选择复制对象"  class="copyObjList">
                        <div class="copy_object flexbox flexcenter" style="margin-bottom: 12px" v-for="(copyObj,index) in copySubFrom">
                            <!-- <div class="adver_name">{{subForm.creatives.ad_name}}</div>
                            <div class="adver_id">广告ID：{{subForm.creatives.ad_id}}</div> -->
                            <div style="width:100%;padding-right: 12px;">
                                <div class="adver_id flexbox flexcenter">
                                    <span style="flex-shrink:0;width: 56px;">广告账户</span> 
                                    <el-select v-model="copyObj.advertiser_id" filterable @visible-change="(is)=>adverListCopy = adverList" :filter-method="filterFn" placeholder="请选择" style="width:100%" popper-class="copy_select" @change="selectUser(index)">
                                        <el-option v-for="item in adverListCopy" :key="item.advertiser_id" :label="item.advertiser_name" :value="item.advertiser_id">
                                            <div class="user_name">{{item.advertiser_name}}</div>
                                            <div class="user_id">账户ID：{{item.advertiser_id}}</div>
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="adver_id flexbox flexcenter">
                                    <span style="flex-shrink:0;width: 56px;">广告系列</span>
                                   <el-select 
                                    v-model="copyObj.campaign_id" 
                                    :disabled="!copyObj.advertiser_id" 
                                    filterable 
                                    remote 
                                    reserve-keyword
                                    clearable
                                    value-key="ad_id" 
                                    placeholder="请输入广告 ID 搜索"
                                    style="width:100%" 
                                    class="aweme_el_select" 
                                    @visible-change="(is) => getCampaignList(is,copyObj.advertiser_id,index)" 
                                    @clear="() => fillData(index)"
                                    popper-class="copy_select_partner" 
                                    :remote-method="(query) => remoteMethod(query,copyObj.advertiser_id,index)" 
                                    :loading="s_loading" 
                                    @focus="handleFocus">
                                    <!-- <template slot="prefix">
                                        <div class="aweme_icon" style="line-height:50px">
                                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M12.0208 11.0782L14.4044 13.4612C14.665 13.7217 14.665 14.144 14.4045 14.4045C14.144 14.665 13.7217 14.665 13.4612 14.4044L11.0782 12.0208C10.016 12.8723 8.69483 13.3354 7.3335 13.3335C4.0215 13.3335 1.3335 10.6455 1.3335 7.3335C1.3335 4.0215 4.0215 1.3335 7.3335 1.3335C10.6455 1.3335 13.3335 4.0215 13.3335 7.3335C13.3354 8.69483 12.8723 10.016 12.0208 11.0782ZM10.6835 10.5835C11.5296 9.71342 12.0021 8.54712 12.0002 7.3335C12.0002 4.75483 9.9115 2.66683 7.3335 2.66683C4.75483 2.66683 2.66683 4.75483 2.66683 7.3335C2.66683 9.9115 4.75483 12.0002 7.3335 12.0002C8.54712 12.0021 9.71342 11.5296 10.5835 10.6835L10.6835 10.5835Z" fill="#616C85" />
                                            </svg>
                                        </div>
                                    </template> -->
                                    <el-option v-for="item in copyObj.adverOption" :key="item.campaign_id" :label="item.campaign_name" :value="item.campaign_id">
                                        <div class="">
                                            <div class="user_name">{{item.campaign_name}}</div>
                                            <div class="user_id">广告ID：{{item.campaign_id}}</div>
                                        </div>
                                    </el-option>
                                     <el-option v-if="!copyObj.adverOption.length" disabled value="">  
                                        <div style="text-align: center;color: #999;font-size: 14px;">暂无数据</div>
                                    </el-option>  
                                </el-select>
                                </div>
                            </div>
                            <svg class="delete_icon" v-if="copySubFrom.length != 1" @click="deleteAdver(index)" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.57031 8.14369L9.02746 5.57227H14.9703L15.4275 8.14369" stroke="#B4B7BD" stroke-width="1.37143" stroke-linejoin="round" />
                                <path d="M6 8.14258H18" stroke="#B4B7BD" stroke-width="1.44361" stroke-linecap="round" />
                                <path fill-rule="evenodd" clip-rule="evenodd" d="M16.2863 8.14258L15.6269 18.4283H8.37418L7.71484 8.14258H16.2863Z" stroke="#B4B7BD" stroke-width="1.37143" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M10.2852 15.4277H13.7137" stroke="#B4B7BD" stroke-width="1.37143" stroke-linecap="round" />
                            </svg>
                        </div>
                        <div class="flexbox flexcenter flexjust" style="background: rgba(165, 177, 209, 0.1);margin-top:12px;border-radius: 4px;cursor: pointer;" @click="addFrom">
                            <svg xmlns="http://www.w3.org/2000/svg" width="21" height="20" viewBox="0 0 21 20" fill="none">
                             <path d="M11.332 4.79232C11.332 4.33208 10.9589 3.95898 10.4987 3.95898C10.0385 3.95898 9.66536 4.33208 9.66536 4.79232V9.16732H5.29036C4.83013 9.16732 4.45703 9.54041 4.45703 10.0007C4.45703 10.4609 4.83013 10.834 5.29036 10.834H9.66536V15.209C9.66536 15.6692 10.0385 16.0423 10.4987 16.0423C10.9589 16.0423 11.332 15.6692 11.332 15.209V10.834H15.707C16.1673 10.834 16.5404 10.4609 16.5404 10.0007C16.5404 9.54041 16.1673 9.16732 15.707 9.16732H11.332V4.79232Z" fill="#5C636C"/>
                            </svg>
                            <div>添加复制对象</div>
                        </div>
                    </el-form-item>
                    <el-form-item label="复制次数" prop="adgroup_num">
                        <el-input-number v-model="subForm.adgroup_num" controls-position="right" :min="1" :max="100" style="width:100px"></el-input-number>
                    </el-form-item>
                    <!-- <el-form-item label="复制到广告账户" prop="advertiser_ids" :rules="{required: true, message: '请选择', trigger: ['blur', 'change']}">
                        <el-select v-model="subForm.advertiser_ids" placeholder="请选择" style="width:100%" multiple collapse-tags filterable>
                            <el-option v-for="item in adverList" :key="item.advertiser_id" :label="item.advertiser_name" :value="item.advertiser_id">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                    <!-- <el-form-item label="" prop="">
                        <div class="flexbox flexcenter num_icon">
                            <div class="flex">
                                <el-form-item label="新建广告系列数量" prop="campaign_num">
                                    <el-input-number v-model="subForm.campaign_num" controls-position="right" :min="1" :max="100" style="width:100px"></el-input-number>
                                </el-form-item>
                            </div>
                            <div class="flex">
                                <el-form-item label="新建广告组数量" prop="adgroup_num">
                                    <el-input-number v-model="subForm.adgroup_num" controls-position="right" :min="1" :max="100" style="width:100px"></el-input-number>
                                </el-form-item>
                            </div>
                            <div class="flex">
                                <el-form-item label="广告数量" prop="creatives_num">
                                    <el-input-number v-model="subForm.creatives_num" controls-position="right" :min="1" :max="20" style="width:100px"></el-input-number>
                                </el-form-item>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="广告系列状态设置" :prop="`base_json.operation_status`">
                        <el-switch class="cust_switch" width="28" v-model="subForm.base_json.operation_status" active-value="ENABLE" inactive-value="DISABLE">
                        </el-switch>
                    </el-form-item> -->
                    <el-form-item label="开投放始时间" :prop="`base_json.create_time`" :rules="{required: true, message: '请选择', trigger: ['blur', 'change']}">
                        <el-date-picker :clearable="false" v-model="subForm.base_json.create_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" :picker-options="pickerOptions" style="width:250px">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="系统任务名称" prop="name" :rules="{required: true, message: '请输入', trigger: ['blur', 'change']}">
                        <el-input v-model="subForm.name" placeholder="创建后将生成任务记录，请设置任务名称">
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="copy_right flexbox flexcenter flexjust flexcolumn">
                <!-- <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.advertiser_ids.length}}</div>
                    <div class="num_title">广告账户</div>
                </div>  -->
                <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{copySubFrom.length}}</div>
                    <div class="num_title">广告账户/系列</div>
                </div>
                <svg class="equat_icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="0.5">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M14 3.66667L12.3333 2L8 6.33333L3.66667 2L2 3.66667L6.33333 8L2 12.3333L3.66667 14L8 9.66667L12.3333 14L14 12.3333L9.66667 8L14 3.66667Z" fill="#165DFF" />
                    </g>
                </svg>
                 <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.creatives.length}}</div>
                    <div class="num_title">目标创意数/组</div>
                </div>
                 <svg class="equat_icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="0.5">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M14 3.66667L12.3333 2L8 6.33333L3.66667 2L2 3.66667L6.33333 8L2 12.3333L3.66667 14L8 9.66667L12.3333 14L14 12.3333L9.66667 8L14 3.66667Z" fill="#165DFF" />
                    </g>
                </svg>
                 <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.adgroup_num}}</div>
                    <div class="num_title">复制次数</div>
                </div>
                
                <!-- <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.campaign_num}}</div>
                    <div class="num_title">广告系列</div>
                </div>
                <svg class="equat_icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="0.5">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M14 3.66667L12.3333 2L8 6.33333L3.66667 2L2 3.66667L6.33333 8L2 12.3333L3.66667 14L8 9.66667L12.3333 14L14 12.3333L9.66667 8L14 3.66667Z" fill="#165DFF" />
                    </g>
                </svg>
                <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.adgroup_num}}</div>
                    <div class="num_title">广告组</div>
                </div>
                <svg class="equat_icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="0.5">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M14 3.66667L12.3333 2L8 6.33333L3.66667 2L2 3.66667L6.33333 8L2 12.3333L3.66667 14L8 9.66667L12.3333 14L14 12.3333L9.66667 8L14 3.66667Z" fill="#165DFF" />
                    </g>
                </svg>
                <div class="copy_count flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{subForm.creatives_num}}</div>
                    <div class="num_title">广告</div>
                </div> -->
                <svg class="equat_icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="0.5">
                        <rect y="3" width="16" height="3" fill="#165DFF" />
                        <rect y="10" width="16" height="3" fill="#165DFF" />
                    </g>
                </svg>
                <div class="copy_count copy_count_blue flexbox flexcenter flexjust flexcolumn">
                    <div class="num_text">{{getTotal}}</div>
                    <div class="num_title">复制广告条数</div>
                </div>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="resetForm('copyForm')" class="el-button-width">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm('copyForm')" :disabled="loading" :loading="loading" class="el-button-width">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
export default {
    props: ["subForm", "adverList"],
    name: "",
    data() {
        return {
            loadingMore:false,
            adverListCopy:this.adverList,
            queryInfo:{
                page:1,
                advertiser_id:''
            },
            MoreIndex:0,
            s_loading:false,
            copySubFrom:[{advertiser_id:'',campaign_id:'',adverOption:[]}],
            loading: false,
            dialogVisible: false,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
                },
            },
        };
    },
    computed: {
        getTotal() {
            return (
                // this.subForm.advertiser_ids.length*
                // this.subForm.campaign_num *
                // this.subForm.adgroup_num *
                // this.subForm.creatives_num
                this.copySubFrom.length *
                this.subForm.creatives.length *
                this.subForm.adgroup_num
            );
        },
    },
    created() {},
    methods: {
        searchAdvertiser(keyword,SearchArr) {
            // 创建一个正则表达式，忽略大小写，并匹配包含关键字的内容
            const regex = new RegExp(keyword, 'i');
            // 用于存储匹配结果的数组
            const matches = [];

            // 遍历数组对象
            for (let i = 0; i < SearchArr.length; i++) {
                const advertiser = SearchArr[i];
                // 检查 advertiser_id 或 advertiser_name 是否匹配关键字
                if (regex.test(advertiser.advertiser_id) || regex.test(advertiser.advertiser_name)) {
                    // 如果找到匹配的对象，则将其添加到匹配结果数组中
                    matches.push(advertiser);
                }
            }
            // 返回匹配结果数组
            return matches;
        },
        filterFn(serach){
          this.adverListCopy = this.searchAdvertiser(serach,this.adverList)
        },
        selectUser(index){
          this.copySubFrom[index].campaign_id = "";
          this.copySubFrom[index].adverOption = [];
        },
        fillData(index){
            this.copySubFrom[index].adverOption = [];
            this.s_loading = true;
            this.$http.get(this.$tiktokUrl + 'launch/TiktokInfo/campaignList',{params:{...this.queryInfo,page:1}}).then(e=>{
                    if (e.data.code !== 200) {
                    this.s_loading = false;
                    this.$message.error(res.msg);
                    return;
                } else {
                    this.s_loading = false;
                    if(e.data.data.list.length>0){
                        this.copySubFrom[index].adverOption = e.data.data.list
                    }
                }
            })
        },
        getCampaignList(is,id,index){
             this.s_loading = true;
            if(is){
                this.MoreIndex = index
                this.queryInfo.advertiser_id = id
                if(this.copySubFrom[index].adverOption.length == 0){
                    this.$http.get(this.$tiktokUrl + 'launch/TiktokInfo/campaignList',{params:{...this.queryInfo,page:1}}).then(e=>{
                        if (e.data.code !== 200) {
                            this.s_loading = false;
                            this.$message.error(res.msg);
                            return;
                        } else {
                            this.s_loading = false;
                            if(e.data.data.list.length>0){
                                this.copySubFrom[index].adverOption = e.data.data.list
                            }
                        }
                    })
                }else{
                    
                    this.s_loading = false;
                }
            }
        },
        deleteAdver(i){
            this.copySubFrom.splice(i,1)
        },
        addFrom(){
            // document.
            this.copySubFrom.push({advertiser_id:'',campaign_id:'',adverOption:[]})
        },
        handleFocus(event) {
            document.getElementsByClassName('copy_select_partner')[0].children[0].children[0].addEventListener('scroll', this.handleScroll);
            },
         throttle(func, limit = 500) {
            let inThrottle;
            return (...args) => {
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            };
        },
        handleScroll(event) {
            const { scrollHeight, scrollTop, clientHeight } = event.target;
            const throttledLoadMore = this.throttle(() => {
                if (!this.loadingMore && scrollHeight - (scrollTop + clientHeight) < 20) { // 距离底部10px时加载更多
                    this.loadMore();
                }
            });

            throttledLoadMore();
        },
        async loadMore() {
            this.queryInfo.page++
            this.loadingMore = true;
            const { data: res } = await this.$http.post(this.$tiktokUrl + 'launch/TiktokInfo/campaignList',this.queryInfo);
            if (res.code !== 200) {
                this.loadingMore = false;
               return this.$message.error(res.msg);
            } else {
                this.loadingMore = false;
                this.copySubFrom[this.MoreIndex].adverOption = [...this.copySubFrom[this.MoreIndex].adverOption,...res.data.list];
            }
        },
        remoteMethod(query,advertiser_id,index) {
            if (query !== "") {
                this.getAdverList(query,advertiser_id,index);
            }
        },
        // 获取广告
        async getAdverList(report_name,advertiser_id,index) {
            this.s_loading = true;
          const { data: res } = await this.$http.post(this.$tiktokUrl + 'launch/TiktokInfo/campaignList',{
                    page:1,
                    advertiser_id: advertiser_id,
                    campaign_id: report_name,
                })
            // const { data: res } = await this.$http.post(
            //     this.$tiktokUrl + "launch/TiktokLaunch/adGet",
            //     {
            //         advertiser_id: id,
            //         ad_id: report_name,
            //     }
            // );
            if (res.code !== 200) {
                this.s_loading = false;
                this.$message.error(res.msg);
                return;
            } else {
                this.s_loading = false;
                this.copySubFrom[index].adverOption = res.data.list
            }
        },
        getData() {
            this.dialogVisible = true;
        },
        // 提交添加
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    for (let index = 0; index < this.copySubFrom.length; index++) {
                      if(this.copySubFrom[index].campaign_id == ''){
                          return  this.$message.error('请填写完整复制对象内容！');
                       }
                    }
                   this.subForm.creatives = this.subForm.creatives.map(e=>{
                        return {
                            adgroup_id:e.adgroup_id,
                            ad_name:e.ad_name,
                            ad_id:e.ad_id,
                            bid_price:e.bid_price,
                        }
                    })
                   
                    this.subForm.advertiser_ids = this.copySubFrom.map(e=>{
                        return{
                            advertiser_id:e.advertiser_id,
                            campaign_id:e.campaign_id
                        }
                    })

                    console.log(this.subForm)
                    this.loading = true;
                    const { data: res } = await this.$http.post(
                        this.$tiktokUrl + "launch/TiktokLaunch/planCopy",
                        this.subForm
                    );
                    if (res.code !== 200) {
                        this.loading = false;
                        this.$message.error(res.msg);
                        return;
                    } else {
                        this.$message({
                            message: "复制成功",
                            type: "success",
                        });
                        this.$router.push({
                            path: "/copy_list",
                        });
                    }
                } else {
                    this.loading = false;
                    return false;
                }
            });
        },

        // 关闭重置表单
        resetForm(formName) {
            this.dialogVisible = false;
        },
    },
    components: {},
};
</script>

<style>
.copy_select_partner .el-select-dropdown__item {
    height: auto;
    padding-top: 10px;
    padding-bottom: 10px;
}
</style>
<style scoped>
.user_name {
    font-size: 14px;
    line-height: 20px;
    height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.user_id {
    font-size: 12px;
    color: #b4b7bd;
    line-height: 17px;
    margin-top: 4px;
}
.copy_left{
    overflow: auto;
    max-height: 532px;
}
.delete_icon{
    cursor: pointer;
}
/deep/ .adver_id .el-input__inner {
    border: none;
    height: 32px;
    line-height: 32px;
    padding-left: 15px;
}
/deep/ .adver_id .el-input.is-disabled .el-input__inner{
        background-color: #FFF;
}
.copy_right {
    width: 200px;
}
.copy_left {
    padding: 20px 20px 0;
    border-right: 1px solid #ebebeb;
}
.copy_box {
    margin: -20px -20px 0;
    border-bottom: 1px solid #ebebeb;
}
.copy_object {
    padding: 12px;
    background: rgba(165, 177, 209, 0.1);
    border-radius: 4px;
}
.adver_name {
    font-size: 14px;
    line-height: 20px;
    height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.adver_id {
    font-size: 12px;
    color: #b4b7bd;
    line-height: 17px;
}
.adver_id:nth-child(1){
    margin-top: 4px;
}
.adver_id:nth-child(2){
    margin-top: 12px;
}
.copy_count {
    width: 112px;
    height: 62px;
    background: rgba(68, 117, 255, 0.05);
    border-radius: 6px;
}

.num_text {
    font-size: 16px;
    height: 12px;
    line-height: 12px;
    color: #17233d;
    font-family: D-DIN;
    font-weight: 700;
}
.num_title {
    font-size: 12px;
    color: #616c85;
    line-height: 17px;
    height: 17px;
    margin-top: 8px;
}
.copy_count_blue {
    background: #4475ff;
}
.copy_count_blue .num_text {
    color: #fff;
}
.copy_count_blue .num_title {
    color: #fff;
    opacity: 0.8;
}
.equat_icon {
    margin: 10px 0;
}
/deep/ .num_icon .el-icon-arrow-up:before {
    content: "\e78f";
}
</style>
